package utils

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"os/exec"
)

// CmdSingle 执行单行命令，等待命令全部执行完后返回
//
//	shell	eg:	`ls	-la`	or	`ps	-ef	|	grep	server`
//	string exec result
func CmdSingle(shell string) (string, error) {
	cmd := exec.Command("/bin/bash", "-c", shell)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return "", err
	}
	defer stdout.Close()

	cmd.Start()

	// 按行读
	reader := bufio.NewReader(stdout)
	result := ""
	for {
		line, err2 := reader.ReadString('\n')
		if err2 != nil || io.EOF == err2 {
			break
		}
		result += line
	}

	cmd.Wait()
	return result, nil
}

// CmdQuick 快速执行一行命令，不等待立即返回
func CmdQuick(shell string) (string, error) {
	cmd := exec.Command("/bin/bash", "-c", shell)
	out, err := cmd.Output()
	if err != nil {
		fmt.Printf("%s %s\n", shell, err.Error())
		return "", err
	}
	return string(out), nil
}

// CmdNohup 执行 nohup 命令
func CmdNohup(shell string) error {
	f, _ := os.Create("nohup")
	cmd := exec.Command("/bin/bash", "-c", shell)
	cmd.Stdout = os.Stdout
	cmd.Stderr = f
	err := cmd.Run()
	if err != nil {
		fmt.Printf("%s %s\n", shell, err.Error())
		return err
	}
	return nil
}

// CmdMulti 顺序运行多条命令
func CmdMulti(multiCmd []string) (string, error) {
	result := ""
	for _, cmd := range multiCmd {
		single, err := CmdSingle(cmd)
		if err != nil {
			fmt.Printf("%s %s\n", single, err.Error())
		} else if single != "" {
			fmt.Println(single)
		}
		result += single
	}

	return result, nil
}
